import { Button, Card, message, Tree } from 'antd';
import React, { useEffect, useState } from 'react';
import request from '@/utils/request';
import NameModal from '@/components/NameModal';
import DirectoryTree from '@/components/Folder';

const topNode = { 1: true, 2: true, 3: true };

const TemplateCat = (props) => {
  const { onSelect } = props;

  const [treeData, setTreeData] = useState([]);
  const [fetching, setFetching] = useState(false);
  const [selectedNode, setSelectedNode] = useState();
  const [visible, setVisible] = useState(false);

  const handleSelect = (node) => {
    setSelectedNode(node);
    if (onSelect) {
      onSelect(node.key, node);
    }
  };

  const loadTreeData = async () => {
    const response = await request(`/eofficeserver/api/templates/cat`);
    setTreeData(response);
  };

  useEffect(() => {
    setFetching(true);
    loadTreeData();
    setFetching(false);
  }, []);

  const onCreate = async (values) => {
    setVisible(false);
    setFetching(true);
    const response = await request('/eofficeserver/api/templates/cat', {
      method: 'POST',
      data: { name: values.name, type: selectedNode && selectedNode.key },
    });
    if (!response.success) {
      message.error(response.msg);
    } else {
      loadTreeData();
    }
    setFetching(false);
  };

  return (
    <Card title="模板分类" loading={fetching}>
      <DirectoryTree
        onNodeSelect={handleSelect}
        treeData={treeData}
        titleRender={(nodeData) => {
          return (
            <div>
              {nodeData.title}
              {selectedNode?.key === nodeData.key && topNode[nodeData.key] && (
                <Button
                  type="link"
                  style={{ color: 'white' }}
                  onClick={(e) => {
                    e.stopPropagation();
                    setVisible(true);
                  }}
                >
                  添加分类
                </Button>
              )}
            </div>
          );
        }}
      />
      <NameModal
        title="新建分类"
        initialValue={{ name: '新建分类' }}
        label="分类名称"
        visible={visible}
        onCreate={onCreate}
        onCancel={() => {
          setVisible(false);
        }}
      />
    </Card>
  );
};

export default TemplateCat;
